import { Switch, Button, Popconfirm } from 'antd'
import { Table } from '@/desktop/components'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { WhitelistCorp } from '@/services/features/corp-whitelist'
import { Edit } from './edit'

function CorpWhiteListCom() {
  const { corpWhitelist } = useMemo(() => services.features, [])
  const [enable, whitelist] = useStreams(corpWhitelist.enable, corpWhitelist.list)
  useEffect(() => {
    void corpWhitelist.getStatus()
    void corpWhitelist.load()
  }, [])

  const [editing, setEditing] = useState<true | WhitelistCorp | null>(null) // true: 新增  WhitelistCorp: 编辑  null: 空白
  const startEdit = useCallback((target?: WhitelistCorp) => setEditing(target ?? true), [])
  const finishEdit = useCallback(() => setEditing(null), [])

  function renderActions(corp: WhitelistCorp) {
    return <>
      <Button type="link" onClick={() => startEdit(corp)} disabled={enable !== true}>
        编辑
      </Button>

      <Popconfirm
        title="确认把此主体从白名单中移除吗？"
        onConfirm={async () => corpWhitelist.remove(corp.id)}
        disabled={enable !== true}
      >
        <Button type="link" danger disabled={enable !== true}>
          移除
        </Button>
      </Popconfirm>
    </>
  }

  return <>
    <section css={s.status}>
      <label className="settings-label">启用登录白名单：</label>
      <Switch
        checked={enable ?? false}
        onChange={async () => corpWhitelist.updateStatus(!(enable ?? false))}
        checkedChildren="启用"
        unCheckedChildren="未启用"
      />
    </section>

    <section css={s.add}>
      <Button type="primary" onClick={() => startEdit()} disabled={!(enable ?? false)}>
        添加企微主体
      </Button>
    </section>

    <Table<WhitelistCorp>
      rowKey="id"
      dataSource={whitelist ?? []}
      scroll={{ y: 300 }}
      pagination={false}
      css={s.table}
    >
      <Table.Column<WhitelistCorp> title="CorpId" dataIndex="corpid" width={220} />
      <Table.Column<WhitelistCorp> title="描述" dataIndex="desc" className="desc" />
      <Table.Column<WhitelistCorp>
        title="操作"
        width={200}
        className="actions"
        render={renderActions}
      />
    </Table>

    <Edit editing={editing} onFinish={finishEdit} />
  </>
}
export { CorpWhiteListCom as CorpWhiteList }

const s = {
  status: css`
    display: flex;
    align-items: center;
    margin-bottom: 32px;
  `,
  add: css`
    margin-bottom: 18px;
  `,
  table: css`
    td.desc {
      color: #aaa;
    }
    td.actions button {
      margin-right: 18px;
      padding: 3px 0;
      &:last-child {
        margin-right: 0;
      }
    }
  `,
}
